package com.fingard.dsp.bank.directbank.jsjnrcb01;

import com.fingard.dsp.bank.directbank.FailCode;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.detail.RetAtsBatPayRecDetail;
import com.fingard.dsp.bank.reqrespobj.single.detail.ReqPayRecDetail;
import com.fingard.net.ConnState;
import com.fingard.text.StringHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

/**
 * @author Parker on 2019/7/26.
 * @version 1.0
 */
public class JSJNRCB01BatPayRec extends JSJNRCB01Base implements IBatPayRec {
    @Override
    public RetAtsBatPayRec d_1988_BatPay(ReqBatPayRec p_req1988) throws Exception {
        RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_req1988.reqHeader);
        try {
            JSJNRCB01Header tmpBnkHeader = new JSJNRCB01Header();
            String opName = "B2EBatchTransfer";
            tmpBnkHeader.TransCode = opName;
            tmpBnkHeader.reqSeqNo = p_req1988.reqBatchNO;
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            //需要进行对账码拼接以及节点解析，采用XElement进行处理
            writeCommenHeader(xmlWriter, tmpBnkHeader);
            xmlWriter.autoFormat = false;
            xmlWriter.writeStartElement("Body");
            xmlWriter.writeStartElement("List");
            while (p_req1988.readRecord()) {
                XElement tmpXElement = new XElement("Map", "");
                ReqPayRecDetail tmpDetail = p_req1988.readedDetail;
                // 转账类型 (2122资金划拨 2120--对外转帐 网银不处理该项 001行内转账 002跨行转账)
                String TransferType = "";
                if (tmpDetail.sameBnk != null && tmpDetail.sameBnk.equals("1")) {
                    TransferType = "001";
                } else if (tmpDetail.sameBnk != null && tmpDetail.sameBnk.equals("0")) {
                    TransferType = "002";
                } else if (tmpDetail.innerPay != null && tmpDetail.innerPay.equals("1")) {
                    TransferType = "2122";
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = "转账类型未知";
                    break;
                }
                tmpXElement.addChild(new XElement("TransferType", TransferType));//转帐类型（2122资金划拨 2120--对外转帐 网银不处理该项)
                tmpXElement.addChild(new XElement("TransferJnlNo", tmpDetail.askNumber));
                tmpXElement.addChild(new XElement("PayerAcNo", tmpDetail.payAct));
                if (TransferType.equals("002") && !StringHelper.hasAnyChar(tmpDetail.payName)) {
                    retAts.respCode = "-1";
                    retAts.respInfo = "跨行转账时，付款方帐户名不能为空";
                    break;
                }
                tmpXElement.addChild(new XElement("PayerAcName", tmpDetail.payName));// 跨行转账，不可为空
                tmpXElement.addChild(new XElement("PayerCurrency", convertCurToBank(tmpDetail.payCur)));//币种 做映射
                tmpXElement.addChild(new XElement("PayerBankAcType", ""));
                tmpXElement.addChild(new XElement("PayeeAcName", tmpDetail.recName));
                tmpXElement.addChild(new XElement("PayeeAcNo", tmpDetail.recAct));
                tmpXElement.addChild(new XElement("PayeeBankAcType", ""));
                tmpXElement.addChild(new XElement("Amount", tmpDetail.payAmount));
                if (TransferType.equals("002") && !StringHelper.hasAnyChar(tmpDetail.payName)) {
                    retAts.respCode = "-1";
                    retAts.respInfo = "跨行转账时，收款人行号不能为空";
                    break;
                }
                tmpXElement.addChild(new XElement("UnionDeptId", tmpDetail.recBankCode));
                //默认加急标志为1（ 0：普通 1：加急 2：实时）目前固定为1
                tmpXElement.addChild(new XElement("Priority", "1"));//加急标志 跨行转账，不可为空
                //备注不超过40字
                tmpXElement.addChild(new XElement("Remark", tmpDetail.memo));
                nodeAnalysis(tmpDetail.srcXElement, tmpXElement, getCharset());

                xmlWriter.writeXElement(tmpXElement);
            }
            xmlWriter.writeEndDocument();//写入报文完成
            sendBank(xmlWriter, retAts, opName);
        } catch (Exception e) {
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(e.getMessage());
            e.printStackTrace();
        }
        retAts.writeRetToATS();
        return retAts;
    }

    @Override
    public RetAtsQryBatPayRec d_1998_QryBatPay(ReqQryBatPayRec p_req1998) throws Exception {
        RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_req1998.reqHeader);
        retAts.reqSeqID = p_req1998.reqBatchNO;
        JSJNRCB01Header tmpBnkHeader = new JSJNRCB01Header();
        String opName = "B2EBatchTrsResQry";
        tmpBnkHeader.TransCode = opName;
        try {
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            writeCommenHeader(xmlWriter, tmpBnkHeader);
            xmlWriter.writeStartElement("Body");
            String HistoryERPJnlNo = StringHelper.padRight(p_req1998.reqBatchNO,16,'0');
            xmlWriter.writeElementString("HistoryERPJnlNo", HistoryERPJnlNo);//客户流水号
            xmlWriter.writeEndDocument();
            String[] tmpRetBkStr = sendToBank(xmlWriter.toXmlString(), opName);
            if (tmpRetBkStr[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpRetBkStr[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String returnCode = tmpBkReader.getFirstText("/Message/Head/IBSReturnCode");
                    String returnMsg = tmpBkReader.getFirstText("/Message/Head/IBSReturnMsg");
                    if (returnCode != null && returnCode.equals("000000")) {
                        while (tmpBkReader.read("/Message/Body/List/Map")) {
                            RetAtsBatPayRecDetail retDetail = new RetAtsBatPayRecDetail();
                            retDetail.payAct = tmpBkReader.readedXElement.getSingleText("PayerAcNo");
                            retDetail.recAct = tmpBkReader.readedXElement.getSingleText("PayeeAcNo");
                            retDetail.recName = tmpBkReader.readedXElement.getSingleText("PayeeAcName");
                            retDetail.payAmount = tmpBkReader.readedXElement.getSingleText("Amount");
                            retDetail.payInfoCode = tmpBkReader.readedXElement.getSingleText("ReturnCode");
                            retDetail.result = tmpBkReader.readedXElement.getSingleText("ReturnCode");
                            retDetail.postScript = tmpBkReader.readedXElement.getSingleText("ReturnMsg");
                            retAts.writeRetDetail(retDetail);
                        }
                    } else {
                        retAts.respCode = "-1";
                        retAts.respInfo = returnMsg;
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = tmpSbMsg.toString();
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = tmpRetBkStr[1];
            }
        } catch (Exception ex) {
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
        }
        retAts.writeAfterDetail();
        return retAts;
    }

    @Override
    public RetAtsBatPayRec d_9188_BatPay(ReqBatPayRec p_req9188) throws Exception {
        return null;
    }

    @Override
    public RetAtsQryBatPayRec d_9198_QryBatPay(ReqQryBatPayRec p_req9198) throws Exception {
        return null;
    }


    public void sendBank(XmlTextWriter xmlWriter, RetAtsBatPayRec retAts, String opName) throws Exception {
        String[] tmpStrRet = sendToBank(xmlWriter.toXmlString(), opName);//发送银行
        if (tmpStrRet[0].length() == 0) {
            StringBuilder tmpSbMsg = new StringBuilder();
            //解析银行返回
            XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
            if (tmpBkReader != null) {
                String returnCode = tmpBkReader.getFirstText("/Message/Head/IBSReturnCode");
                String returnMsg = tmpBkReader.getFirstText("/Message/Head/IBSReturnMsg");
                if (returnCode != null && returnCode.equals("000000")) {
                    retAts.transState = "000002";
                    retAts.payInfoCode = "000002";
                } else if (returnCode != null) {
                    retAts.transState = returnCode;//返回码;
                    retAts.payInfoCode = returnCode;//返回码;
                    retAts.respInfo = returnMsg;//返回信息
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = "银行返回信息有误";
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = tmpSbMsg.toString();
            }
        } else if (tmpStrRet[0].equals(ConnState.FAIL)) {
            retAts.respCode = "-1";
            retAts.respInfo = tmpStrRet[1];
        } else {
            retAts.respCode = "-1";
            retAts.respInfo = tmpStrRet[1];
        }
    }
}
